package com.uzai.console.queue;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @author mingyang.chen create in 2024/3/25 19:14
 */
@Component
@Slf4j
public class ConsoleDelayConsumer implements Runnable {

    @Qualifier("taskExecutor")
    @Autowired
    TaskExecutor taskExecutor;

    @PostConstruct
    public void start() {
        Thread thread = new Thread(this);
        thread.setName("console-delay-consumer");
        thread.start();
    }

    @Override
    public void run() {
        log.info("启动内置延迟消费器...");
        for (; ; ) {
            try {
                ConsoleDelayTask take;
                try {
                    take = ConsoleDelayProducer.getDelayQueue().take();
                } catch (InterruptedException e) {
                    log.error("从延时队列中获取任务失败");
                    continue;
                }
                log.info("获取到任务: {}", take);
                if (Objects.nonNull(take.getRun())) {
                    taskExecutor.execute(take.getRun());
                }
            } catch (Exception e) {
                log.error("延时队列消费出现异常", e);
            }
        }
    }
}
